package handle

import (
	"encoding/json"
	"repo-nav/cache"
	"repo-nav/model"
	"repo-nav/pkg"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "login" + username
	errData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errData >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "错误超过 3 次,禁止登录",
		})
		return
	}
	var user model.User
	err := model.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)

		if errData == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, "3", time.Hour*3)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "错误超过 3 次,封禁登录",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"user": user,
	})
	return
}
func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	user := model.RoleNode{

		Rid: rid,
		Nid: nid,
	}
	model.DB.Create(&user)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})

	return
}
func UserRoleList(c *gin.Context) {
	rid := c.Query("rid")
	//SELECT
	//  *
	//FROM
	//  roles
	//  LEFT JOIN user_roles ON user_roles.rid = roles.id
	//  WHERE user_roles.rid=1
	var user model.Role
	model.DB.Table("roles").Joins("LEFT JOIN user_roles ON user_roles.rid = roles.id").
		Where("user_roles.rid = ?", rid).Find(&user)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"user": user,
	})

	return
}
func RoleNodeList(c *gin.Context) {
	nid := c.Query("nid")
	//SELECT
	//  *
	//FROM
	//  nodes
	//  LEFT JOIN role_nodes ON role_nodes.nid = nodes.id
	//  WHERE role_nodes.nid=1
	var user model.Node
	model.DB.Table("nodes").Joins("LEFT JOIN role_nodes ON role_nodes.nid = nodes.id").
		Where("role_nodes.nid = ?", nid).Find(&user)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"user": user,
	})

	return
}
func RopoCreate(c *gin.Context) {
	repo_name := c.PostForm("repo_name")
	repo_address := c.PostForm("repo_address")
	repo_type := c.PostForm("repo_type")
	repo := model.Repo{

		RepoName:    repo_name,
		RepoAddress: repo_address,
		RepoType:    repo_type,
	}
	model.DB.Create(&repo)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})

	return
}
func OrderCreate(c *gin.Context) {
	order_no := c.PostForm("order_no")
	cid, _ := strconv.Atoi(c.PostForm("cid"))
	order_time := c.PostForm("order_time")
	order := model.Order{
		OrderNo:   order_no,
		Cid:       cid,
		OrderTime: order_time,
	}
	model.DB.Create(&order)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})

	return
}
func RepoOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	redis_key := "repo_order_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	//SELECT
	//  orders.id AS Id,
	//  orders.order_no AS OrderNo,
	//  orders.order_time AS OrderTime,
	//  repos.repo_name AS RepoName,
	//  repos.repo_address AS RepoAddress,
	//  repos.repo_type AS RepoType
	//FROM
	//  repos
	//  LEFT JOIN orders ON orders.cid = repos.id

	var orders []model.OrderList
	if cacheData == "" {
		model.DB.Table("repos").Select(
			"orders.id AS Id",
			"orders.order_no AS OrderNo",
			"orders.order_time AS OrderTime",
			"repos.repo_name AS RepoName",
			"repos.repo_address AS RepoAddress",
			"repos.repo_type AS RepoType",
		).Joins("LEFT JOIN orders ON orders.cid = repos.id").Limit(size).
			Offset(offset).Find(&orders)
		jsonData, _ := json.Marshal(offset)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*3)
	} else {
		json.Unmarshal([]byte(cacheData), offset)
	}

	var total int64
	model.DB.Model(&model.Order{}).Count(&total)
	c.JSON(200, gin.H{
		"code":   200,
		"total":  total,
		"orders": orders,
	})
	return
}

func RepoOrderDetail(c *gin.Context) {
	id := c.Query("id")
	redis_key := "repo_order_list" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	var order model.OrderList
	if cacheData == "" {
		model.DB.Table("repos").Select(
			"orders.id AS Id",
			"orders.order_no AS OrderNo",
			"orders.order_time AS OrderTime",
			"repos.repo_name AS RepoName",
			"repos.repo_address AS RepoAddress",
			"repos.repo_type AS RepoType",
		).Joins("LEFT JOIN orders ON orders.cid = repos.id").Where("orders.id = ?", id).Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*3)
	} else {
		json.Unmarshal([]byte(cacheData), order)
	}

	c.JSON(200, gin.H{
		"code":  200,
		"order": order,
	})
	return
}
